<?php include_once( "_db.php" ); //Database ?>
<?php include_once( "funcdef.php" ); //Functions Definition ?>
<?php include_once( "header.php" ); //Header ?>
<?php include_once( "footer.php" ); //Footer ?>
<?php
//include page header
header_template("Photo", $_SERVER['PHP_SELF'], "icon-camera");

//db OBJECT invoked!
$db = new DATABASE();

// File size allowed (max)
$uploadfilemaxsize = 5*1024 *1024;
// File type allowed
$uploadfiletype = array(
                          'gif'  => "image/gif",
                          'jpg'  => "image/jpeg",
                          'png'  => "image/png",
                          'bmp'  => "image/bmp",
                        );
// Where the file is going to be placed
$uploaddir  = "img/";
$uploadfile = $uploaddir . basename(strtolower($_FILES['file']['name']));
// Messages
$msg_upload_error = array(
                            UPLOAD_ERR_OK         => "There is no error, the file uploaded with success.",
                            UPLOAD_ERR_INI_SIZE   => "The uploaded file exceeds the upload_max_filesize directive in php.ini.",
                            UPLOAD_ERR_FORM_SIZE  => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.",
                            UPLOAD_ERR_PARTIAL    => "The uploaded file was only partially uploaded.",
                            UPLOAD_ERR_NO_FILE    => "No file was uploaded.",
                            UPLOAD_ERR_NO_TMP_DIR => "Missing a temporary folder.",
                            UPLOAD_ERR_CANT_WRITE => "Failed to write file to disk.",
                            UPLOAD_ERR_EXTENSION  => "A PHP extension stopped the file upload.",
                          );
$msg_upload_error_size  = "Invalid file. File exceed maximum file size (".($uploadfilemaxsize/1024/1024)." Mb)";
$msg_upload_error_type  = "Invalid file. File is not image (gif/jpg/png/bmp).";
$msg_upload_error_exist = /* $filename." ". */"already exists.";
$msg_upload_error_move  = "Possible file upload attack.";
$msg_upload_success     = "File is valid, and was successfully uploaded";
?>
      <div class="row">
        <div class="span6">
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
//Upload Form
?>
          <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data" class="well form-inline">
            <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $uploadfilemaxsize; ?>" />
            <label for="file">Filename:</label>
            <input type="file" name="file" id="file" class="input-file" />
            <input type="submit" name="upload-photo" value="Upload" class="btn btn-info" />
          </form>
<?php
//Upload File
} elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
  //File type check OK
  if (  ($_FILES["file"]["type"] == $uploadfiletype['gif'])
     || ($_FILES["file"]["type"] == $uploadfiletype['jpg'])
     || ($_FILES["file"]["type"] == $uploadfiletype['png'])
     || ($_FILES["file"]["type"] == $uploadfiletype['bmp'])
     ) {
    //File max size OK
    if ($_FILES["file"]["size"] < $uploadfilemaxsize) {
      //File upload error
      if ($_FILES["file"]["error"] > 0) {
        //File upload error category
        switch ($_FILES["file"]["error"]) {
          case UPLOAD_ERR_OK:
            printAlert("error", "Oh snap!", $msg_upload_error[UPLOAD_ERR_OK], $_SERVER['PHP_SELF']);
            break;
          case UPLOAD_ERR_INI_SIZE:
            printAlert("error", "Oh snap!", $msg_upload_error[UPLOAD_ERR_INI_SIZE], $_SERVER['PHP_SELF']);
            break;
          case UPLOAD_ERR_FORM_SIZE:
            printAlert("error", "Oh snap!", $msg_upload_error[UPLOAD_ERR_FORM_SIZE], $_SERVER['PHP_SELF']);
            break;
          case UPLOAD_ERR_PARTIAL:
            printAlert("error", "Oh snap!", $msg_upload_error[UPLOAD_ERR_PARTIAL], $_SERVER['PHP_SELF']);
            break;
          case UPLOAD_ERR_NO_FILE:
            printAlert("error", "Oh snap!", $msg_upload_error[UPLOAD_ERR_NO_FILE], $_SERVER['PHP_SELF']);
            break;
          case UPLOAD_ERR_NO_TMP_DIR:
            printAlert("error", "Oh snap!", $msg_upload_error[UPLOAD_ERR_NO_TMP_DIR], $_SERVER['PHP_SELF']);
            break;
          case UPLOAD_ERR_CANT_WRITE:
            printAlert("error", "Oh snap!", $msg_upload_error[UPLOAD_ERR_CANT_WRITE], $_SERVER['PHP_SELF']);
            break;
          case UPLOAD_ERR_EXTENSION:
            printAlert("error", "Oh snap!", $msg_upload_error[UPLOAD_ERR_EXTENSION], $_SERVER['PHP_SELF']);
            break;
        }
      } else {//File upload not error
        //File existence NG
        if (file_exists($uploadfile)) {
          printAlert("error", "Oh snap!", $_FILES["file"]["name"]." ".$msg_upload_error_exist, $_SERVER['PHP_SELF']);
        } else {//File existence OK
          //Upload file OK
          if (move_uploaded_file($_FILES["file"]["tmp_name"], $uploadfile)) {
            //UPLOAD SUCCEED!!!
            printAlert("success", "Well done!", $msg_upload_success, $_SERVER['PHP_SELF']);
            //construct INSERT query
            $params = array();
            $params[] = array(1); //$param_col;
            $params[] = array($uploadfile); //$param_key;
            $query = $db->db_insert("picture", $params);
            //execute INSERT query
            $result = $db->database->query($query);
          } else {//Upload file NG
            printAlert("error", "Oh snap!", $msg_upload_error_move, $_SERVER['PHP_SELF']);
          }
        }
      }
    } else {//File max size NG
      printAlert("error", "Oh snap!", $msg_upload_error_size, $_SERVER['PHP_SELF']);
    }
  } else {//File type check NG
    printAlert("error", "Oh snap!", $msg_upload_error_type, $_SERVER['PHP_SELF']);
  }
} else {
  $error_msg = "This script only works with GET and POST requests.";
  printAlert("error", "Oh snap!", $error_msg, $_SERVER['PHP_SELF']);
}

//Delete file
if (isset($_GET["action"]) && isset($_GET["pid"])) {
  if ($_GET["action"] == "delete") {
    //construct SELECT query
    $conds = array();
    $conds[] = array(0); //$param_col;
    $conds[] = array(0); //$param_op;
    $conds[] = array($_GET["pid"]); //$param_key;
    $query = $db->db_select("picture", NULL, $conds);
    //execute SELECT query
    $result = $db->database->query($query);
    //result SELECT query
    $resPic = $result->fetchAll(SQLITE_ASSOC);

    //construct SELECT query
    $conds = array();
    $conds[] = array(1); //$param_col;
    $conds[] = array(0); //$param_op;
    $conds[] = array($_GET["pid"]); //$param_key;
    $query = $db->db_select("picture2product", NULL, $conds);
    //execute SELECT query
    $result = $db->database->query($query);
    //result SELECT query
    $resPic2Prod = $result->fetchAll(SQLITE_ASSOC);

    //check photo to product link OK
    if (empty($resPic2Prod)) {
      //check file existence OK
      if ((!empty($resPic)) && (file_exists($resPic[0]['picture_name']))) {
        //delete file from disk OK
        if (unlink($resPic[0]['picture_name'])) {
          //construct DELETE query
          $conds = array();
          $conds[] = array(0); //$param_col;
          $conds[] = array(0); //$param_op;
          $conds[] = array($_GET["pid"]); //$param_key;
          $query = $db->db_delete("picture", $conds);
          //execute SELECT query
          $result = $db->database->query($query);
          //delete file from databse NG
          if ($result == FALSE) {
            printAlert("error", "Oh snap!", "Cannot delete ".$resPic[0]['picture_name'], $_SERVER['PHP_SELF']);
          } else {//delete file from databse OK
            //DELETE SUCCEED!!!
            printAlert("success", "Well done!", $resPic[0]['picture_name']." successfully deleted", $_SERVER['PHP_SELF']);
          }
        } else {//delete file from disk NG
          printAlert("error", "Oh snap!", "Cannot delete ".$resPic[0]['picture_name'], $_SERVER['PHP_SELF']);
        }
      } else {//check file existence NG
        printAlert("error", "Oh snap!", "Picture not found.", $_SERVER['PHP_SELF']);
      }
    } else {//check photo to product link NG
      printAlert("error", "Oh snap!", "Picture is link to product.", $_SERVER['PHP_SELF']);
    }
  }
}

//Pagination
//set number of pic / page
$picPerPage = 6;
//initialize current page
$curPage = 0;
//set first page
$firstPage = 1;
//initialize last page
$cols = "count";
$conds = NULL;
$query = $db->db_select("picture", $cols, $conds);
//$query = "SELECT count(*) FROM picture";
$rowCount = $db->database->query($query);
$rowCount = $rowCount->fetchAll(SQLITE_NUM);
$rowCount = intval($rowCount[0][0]);
$remainder = intval($rowCount % $picPerPage);
$lastPage = intval($rowCount / $picPerPage);
//set current page
if ((isset($_GET["page"])) && (is_numeric($_GET["page"]))) {
  $curPage = intval($_GET["page"]);
} else {
  $curPage = $firstPage;
}
//set last page
if ($remainder > 0) {
  $lastPage++;
}
if ($lastPage > 1) { //pagination start
?>
          <ul class="pager">
<?php
  if ($curPage != $firstPage) {
    $pager_prev_state = " active";
    $pager_prev_href  = " href=\"".$_SERVER['PHP_SELF']."?page=".($curPage-1)."\"";
  } else {
    $pager_prev_state = " disabled";
    $pager_prev_href  = "";
  }

  if ($curPage != $lastPage) {
    $pager_next_state = " active";
    $pager_next_href  = " href=\"".$_SERVER['PHP_SELF']."?page=".($curPage+1)."\"";
  } else {
    $pager_next_state = " disabled";
    $pager_next_href  = "";
  }
?>
            <li class="previous <?php echo $pager_prev_state; ?>">
              <a<?php echo $pager_prev_href; ?>>&larr; Prev</a>
            </li>
            <li class="next <?php echo $pager_next_state; ?>">
              <a<?php echo $pager_next_href; ?>>Next &rarr;</a>
            </li>
          </ul>
          <center>
            <p><span class="label label-info">Page <?php echo $curPage; ?>/<?php echo $lastPage; ?></span></p>
          </center>
<?php } //pagination end ?>
<?php
//construct SELECT query
$query = $db->db_select("picture", NULL, NULL);
//execute SELECT query
$result = $db->database->query($query." ORDER BY picture_id DESC LIMIT ".(($curPage-1)*$picPerPage).", ".$picPerPage);
/*$result = $db->database->query($query." ORDER BY picture_id DESC");*/
//result SELECT query
$resPic = $result->fetchAll(SQLITE_ASSOC);
//List File(s)
//File(s) existence OK
if (!empty($resPic)) {
?>
          <ul class="thumbnails">
<?php
  //loop trough all file(s)
  foreach ($resPic as $value) {

    //construct SELECT query
    $conds = array();
    $conds[] = array(1); //$param_col;
    $conds[] = array(0); //$param_op;
    $conds[] = array($value['picture_id']); //$param_key;
    $query = $db->db_select("picture2product", NULL, $conds);
    //execute SELECT query
    $result = $db->database->query($query);
    //result SELECT query
    $resPic2Prod = $result->fetchAll(SQLITE_ASSOC);

    $img_src = $value['picture_name'];
    $img_src_resize = "timthumb.php?src=".$img_src."&w=160&h=120&a=t";
    $img_src_resize = "timthumb.php?src=".$img_src."&w=160&h=120&a=t";
    if (empty($resPic2Prod)) {
      $img_delete_href = $_SERVER['PHP_SELF']."?action=delete&pid=".$value['picture_id'];
      $img_delete_lnk_state = "";
    } else {
      $img_delete_href = "#";
      $img_delete_lnk_state = " disabled";
    }
?>
            <li class="span2">
              <div class="thumbnail">
                <img src="<?php echo $img_src_resize; ?>" alt="<?php echo $img_src; ?>">
                <div class="caption">
                  <p><a href="<?php echo $img_src; ?>" class="btn btn-mini" target="_blank">Full Size</a>&nbsp;<a href="<?php echo $img_delete_href; ?>" class="btn btn-mini btn-danger<?php echo $img_delete_lnk_state; ?>">Delete</a></p>
                </div>
              </div>
            </li>
<?php
  }
?>
          </ul>
<?php
}
?>
        </div>
      </div>
<?php
//include page footer
footer_template();
?>
